package com.px.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.px.dal.DemoMapper;
import com.px.interceptor.MemberInterceptor;
import com.px.model.UserInfo;
import com.px.model.demo_UserInfo;
import com.px.unit.JSONHelper;
import com.px.unit.Response;

//把当前类注解为控制器
@Controller
public class HomeController {

	DemoMapper demo = new DemoMapper();

	// 注解请求方法，和请求地址进行绑定，请求地址为http://localhost:8080/项目名称/index
	@RequestMapping("/index")
	public ModelAndView index() {
		// 创建模型与视图类的实例，并通过构造函数初始化绑定的jsp页面
		ModelAndView mv = new ModelAndView("index");
		// 如需给页面绑定数据集
		// 可使用如下方法mv.addObject("catelist", catelist);
		return mv;
	}

	/**
	 * 
	 * 登录请求方法
	 * 前端交互为ajax
	 * */
	@ResponseBody
	@RequestMapping(value = "/validateLogin", method = RequestMethod.POST, produces = "application/json; utf-8")
	public Response validateLogin(UserInfo user, HttpServletRequest request) {
		String username = user.getUser_name();
		String userpass = user.getUser_pass();

		// System.out.println(username + "/" +userpass);
		demo_UserInfo u = demo.validateLogin(username, userpass);
		if (u != null) {
			// 登录成功
			// 设置session
			HttpSession session = request.getSession();
			session.setAttribute(MemberInterceptor.SESSION_MEMBER, JSONHelper.serialize(u));
			return new Response(200, "登录成功", u);
		} else {
			// 登录失败
			return new Response(403, "登录失败");
		}
	}

	/**
	 * 
	 * 后台管理首页请求地址
	 * HttpServletRequest是获取服务器上的session数据，一般我们保存登录用户的数据
	 * @return
	 */
	@RequestMapping("/admin/index")
	public ModelAndView adminindex(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/admin/index");
		UserInfo user = null;
		// 获取session
		HttpSession session = request.getSession();
		if (session.getAttribute(MemberInterceptor.SESSION_MEMBER) != null) {
			// user = session.getAttribute(MemberInterceptor.SESSION_MEMBER).toString();
			user = JSONHelper.deserialize(session.getAttribute(MemberInterceptor.SESSION_MEMBER).toString(),
					UserInfo.class);
		}
		// System.out.println(user);

		mv.addObject("userinfo", user);
		return mv;
	}

	/**
	 * 
	 * 登录页面请求地址
	 * @return
	 */
	@RequestMapping("/login")
	public ModelAndView login() {
		ModelAndView mv = new ModelAndView("/login");
		return mv;
	}
}
